from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup
import csv
import os
import cv2
from PIL import Image
import pytesseract
import numpy as np
import sys
import PIL.Image
from pathlib import Path
import ddddocr
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import base64
from selenium.common.exceptions import TimeoutException

# ===== 添加向后兼容性代码 =====
if not hasattr(PIL.Image, 'ANTIALIAS'):
    PIL.Image.ANTIALIAS = PIL.Image.LANCZOS

def auto_login():

    # 固定账号密码
    username = "temp_d121"
    password = "D121d121d121@"  # 请替换为实际密码

    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")

    # 初始化Chrome驱动
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
    wait = WebDriverWait(driver, 10)

    # 访问登录页面
    login_url = "https://www.i-elitech.net/user/login"
    driver.get(login_url)

    # 找到并填写用户名字段
    username_field = wait.until(EC.presence_of_element_located((By.ID, "userName")))
    username_field.clear()
    username_field.send_keys(username)

    # 找到并填写密码字段
    password_field = wait.until(EC.presence_of_element_located((By.ID, "accountPassword")))
    password_field.clear()
    password_field.send_keys(password)

    # 获取验证码图片
    captcha_img = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "verify-code")))
    captcha_img.screenshot("captcha.png")

    # 初始化ddddocr并识别验证码
    ocr = ddddocr.DdddOcr()
    with open("captcha.png", "rb") as f:
        img_bytes = f.read()
    captcha_text = ocr.classification(img_bytes)

    # 查找并点击登录按钮
    try:
        # 勾选同意服务协议复选框
        agree_checkbox = wait.until(EC.element_to_be_clickable((By.ID, "agree")))
        if not agree_checkbox.is_selected():
            agree_checkbox.click()
        # 点击登录按钮
        login_button = wait.until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'login') or @type='submit']")))
        login_button.click()
    except:
        try:
            agree_checkbox = wait.until(EC.element_to_be_clickable((By.ID, "agree")))
            if not agree_checkbox.is_selected():
                agree_checkbox.click()
            login_button = wait.until(EC.element_to_be_clickable(
                (By.XPATH, "//button[contains(text(), '登录') or contains(text(), 'Login')]")))
            login_button.click()
        except:
            agree_checkbox = driver.find_element(By.ID, "agree")
            if not agree_checkbox.is_selected():
                agree_checkbox.click()
            login_buttons = driver.find_elements(By.XPATH, "//button")
            if login_buttons:
                driver.execute_script("arguments[0].click();", login_buttons[0])


def click_data_window_buttons(driver, timeout=10):
    """
    依次点击“在线设备”->“1030”->“数据图表”按钮，展开数据窗口。

    :param driver: Selenium webdriver 已登录并位于目标页面
    :param timeout: 每次等待元素出现的最长秒数
    """
    wait = WebDriverWait(driver, timeout)

    # 1. 点击 “在线设备” 按钮
    online_device_btn = wait.until(
        EC.element_to_be_clickable(
            (By.XPATH, "//div[contains(@class,'box')]//p[contains(@class,'title') and contains(text(),'在线设备')]")
        )
    )
    online_device_btn.click()

    # 2. 点击 “1030” 设备
    device_btn = wait.until(
        EC.element_to_be_clickable(
            (By.XPATH, "//span[contains(@class,'device-name') and contains(text(),'1030')]")
        )
    )
    device_btn.click()

    # 3. 点击 “数据图表” Tab
    data_chart_tab = wait.until(
        EC.element_to_be_clickable(
            (By.XPATH, "//div[contains(@class,'ant-tabs-tab') and contains(text(),'数据图表')]")
        )
    )
    data_chart_tab.click()

auto_login()
driver = webdriver.Chrome()
click_data_window_buttons(driver)